<?php
class indexControl extends commonControl{
	protected $setup;
	/**
	 * 安装首页  1
	 */
    function index(){
    	$_SESSION['step'] = 1;
        $this->display();
    }
    /**
     * 检查文件可读性和函数 以及软件版本  2
     */
    function check(){
    	if ($_SESSION['step'] < 1) {
    		go("index");
    	}
    	$_SESSION['step'] = 2;
    	$uploadsize = ini_get("upload_max_filesize");//允许上传的单个文件最大值
    	$gd = gd_info();//获得GD库所有信息
    	$gdversion = $gd['GD Version'];//获得GD库版本
    	$diskspace = get_size(disk_free_space('.'));
    	$system = array(
    			"phpversion" => PHP_VERSION,
    			"phpos" => PHP_OS,
    			"uploadsize" => $uploadsize,
    			"gdversion" => $gdversion,
    			"diskspace" => $diskspace
    	);
    	$setpArr = include PATH_APP . '/data/setup.php';
    	foreach($setpArr['dirs'] as $v){ //验证文件的可写行、
    		if(!is_writeable($v)){
    			$_SESSION['step'] = 1;   //只要有一个目录或者文件不可写就将 $_SESSION['step'] 设成1
    		}
    	}
    	$this->assign("system", $system);
    	$this->display();
    }
    /**
     * 配置数据库链接  3
     */
    public function setconfig(){
    	if ($_SESSION['step'] < 2) {
            go("index");
        }
        $_SESSION['step'] = 3;
    	$this->display();
    }
    /**
     * AJAX检测数据库配置 3
     */
    public function checkdb(){
    	$db = mysql_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpwd']);
    	if($db){
    		echo 1;
    	}else{
    		echo 0;
    	}
    }
    /**
     * 安装数据库  4
     */
    public function installdb(){
    	if ($_SESSION['step'] < 3 ) {
            go("setconfig");
        }
        $_SESSION['step'] = 4;
        $_SESSION['admin'] = $_POST['admin'];
        $this->writeconfig();
        $this->display();
    }
    /**
     * 写入数据库配置 4
     */
    public function writeconfig(){
    	$str = '<?php
                if (!defined("PATH_HD"))exit;
                return ';
    	$str.=var_export($_POST['db'], true) . ';?>';
    	$dbconfigfile = "../config/database.php";
    	file_put_contents($dbconfigfile, $str);  ///事后开启此项
    }
    /**
     * 开始创建数据库 5
     */
    public function createtable(){
    	if ($_SESSION['step'] < 3) {
    		go("setconifg");
    	}
    	$_SESSION['step'] = 4;
    	$dbconfig = include "../config/database.php";
    	$dbprefix = $dbconfig['DB_PREFIX']; //表前缀
    	$dbname = $dbconfig['DB_DATABASE'];  //用户填入的数据库名称
    	$sql = file_get_contents(PATH_APP . '/data/bccms.sql');
    	$preg1 = "/(CREATE|USE).*;/sU";
    	preg_match_all($preg1, $sql, $tables);
    	//链接数据库
    	$db = mysql_connect($dbconfig['DB_HOST'], $dbconfig['DB_USER'], $dbconfig['DB_PASSWORD']);
    	//获得缓冲区大小
    	$buffer = ini_get("output_buffering");
    	$error = 0;//错误状态码
    	$tb = array();
    	mysql_query('set names utf8');
    	mysql_query("CREATE SCHEMA IF NOT EXISTS `".$dbname."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;"); //创建数据库
    	mysql_query('use `'.$dbname.'`'); //选择数据库
    	foreach($tables[0] as $t){
    		$pregtable = "/CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+`(.*?)`/iU";
    		preg_match($pregtable, $t,$tb); //能否匹配 table
    		P($tb);
    		echo str_repeat(" ", $buffer); //将缓冲区填满
			if ($tb) {
				$t = preg_replace("/^CREATE\s+TABLE\s+IF NOT EXISTS `.*?`/iU", 'CREATE TABLE IF NOT EXISTS `'.$dbprefix . $tb[1].'` ', $t);
				var_dump($t);
				if (mysql_query($t)) {
					echo "<span style='font-size:14px;height:20px;display:block;width:500px;'>数据表" . $dbprefix . $tb[1] . "创建成功.....</span>";
				}else{
					$error = 1;
					echo "<span style='font-size:14px;height:20px;display:block;width:500px;color:#f00;'>数据表" . $dbprefix . $tb[1] . "创建失败.....</span>";
				}
				sleep(1);
			}
	    	ob_flush();
	    	flush();
    	}
    	if (!$error) {
    		mysql_query("insert into " . $dbprefix."user (username,password,email,regtime) values ('".$_SESSION['admin']['name']."','".md5($_SESSION['admin']['password'])."','".$_SESSION['admin']['email']."','".time()."')");
    		echo "<h3 style='color:#7F9CCC;font-size;22px;'>数据表创建完成</h3>";
    		echo "<script>
	            setTimeout(function(){
	                    parent.window.location.href='" . __CONTROL__ . "/finish';
	            },3000000)
	         </script>";
    	}else{
    		echo "<script>
	            var sub = parent.window.document.getElementById('sub');
    			sub.onclick = function(){
    				return false;
    			}
	         </script>";
    	}
    	exit;
    }
    public function finish(){
    	if ($_SESSION['step'] < 4) {
    		go("index");
    	}
    	$dbconfig = include "../config/database.php";
    	$dbprefix = $dbconfig['DB_PREFIX']; //表前缀
    	$dbname = $dbconfig['DB_DATABASE'];  //用户填入的数据库名称
    	P($dbconfig);
    	$db = mysql_connect($dbconfig['DB_HOST'], $dbconfig['DB_USER'], $dbconfig['DB_PASSWORD']);
    	mysql_query('set names utf8',$db);
    	mysql_query('use `'.$dbname.'`',$db);
    	$sql = file_get_contents(PATH_APP . '/data/config.sql');
    	$preg = '/INTO (`)/isU';
		$sql = preg_replace($preg," INTO `".$dbprefix,$sql);
		$sql_arr = explode(';', $sql);
		foreach($sql_arr as $v){
			mysql_query($v);
		}
		echo mysql_error();
    	unset($_SESSION['step']); //卸载安装步骤
    	file_put_contents(PATH_APP . "/lock", "此文件用来锁住安装程序，如需重新安装程序，请删除此文件");
    	@unlink(PATH_ROOT . "/index.html");
    	$this->display();
    }
}
?>